package com.ksyun.campus.metaserver.services;

import com.alibaba.fastjson.JSONObject;
import com.ksyun.campus.metaserver.config.dataserverconfig.DataServerConfigProperties;
import com.ksyun.campus.metaserver.domain.DataServerInfo;
import com.ksyun.campus.metaserver.util.LoadBalanceUtil;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sxt
 * @version 1.0
 * @description TODO
 * @date 2023/8/11 01:39
 */
public class DefaultDataServerPicker implements IDataServerPicker {
    @Autowired
    private ZkClient zkClient;
    @Autowired
    private DataServerConfigProperties dataServerConfigProperties;
    @Override
    public DataServerInfo pick() {
        List<DataServerInfo> dataServerList = getDataServerList();
        LoadBalanceUtil loadBalanceUtil = new LoadBalanceUtil(dataServerList);
        return loadBalanceUtil.getLoadBalanceServersByFreeRatio();
    }

    /**
     * 获取所有dataserver节点上的dataserver实例信息。
     * @return DataServerInfo列表
     */
    private List<DataServerInfo> getDataServerList(){
        List<String> dsNodeList = zkClient.getChildren(dataServerConfigProperties.getRootName());
        List<DataServerInfo> dataServerInfoList = new ArrayList<>();
        for (String nodeName: dsNodeList) {
            String dataServerInfoJsonStr = (String) zkClient.readData(nodeName);
            DataServerInfo server = JSONObject.parseObject(dataServerInfoJsonStr,DataServerInfo.class);
            dataServerInfoList.add(server);
        }
        return dataServerInfoList;
    }
}
